const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { Sequelize, Op } = require('sequelize');

// 获取总用户数
router.post('/total', async (req, res) => {
    console.log('[userStats] 请求进入 /total');

    try {
        const count = await User.count();
        console.log(`[userStats] 用户总数为: ${count}`);

        res.json({ code: 200, message: '获取成功', data: { totalUsers: count } });
    } catch (error) {
        console.error('[userStats] 获取用户总数失败:', error);
        res.status(500).json({ code: 500, message: '获取用户总数失败', error: error.message });
    }
});

// 获取用户按注册时间的分布（近30天）
router.post('/daily', async (req, res) => {
    console.log('[userStats] 请求进入 /daily');

    try {
        const whereCondition = {
            createdAt: {
                [Op.gte]: Sequelize.literal("DATE_SUB(NOW(), INTERVAL 30 DAY)"),
            },
        };

        console.log('[userStats] 查询条件:', whereCondition);

        const result = await User.findAll({
            attributes: [
                [Sequelize.fn('DATE', Sequelize.col('created_at')), 'date'],
                [Sequelize.fn('COUNT', '*'), 'count'],
            ],
            where: whereCondition,
            group: [Sequelize.fn('DATE', Sequelize.col('created_at'))],
            order: [[Sequelize.fn('DATE', Sequelize.col('created_at')), 'ASC']],
            raw: true,
        });

        console.log('[userStats] 查询结果:', result);

        res.json({ code: 200, message: '获取成功', data: result });
    } catch (error) {
        console.error('[userStats] 获取用户注册分布失败:', error);
        res.status(500).json({ code: 500, message: '获取用户注册分布失败', error: error.message });
    }
});

module.exports = router;
